package com.book.gateway.api.controller;

import com.book.common.api.oauth.HystrixConstant;
import com.book.common.helper.I18nHelper;
import com.book.common.result.Failed;
import com.book.common.result.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * Description：
 *
 * @Author： leo.xiong
 * @CreateDate： 2019/10/15 16:46
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
@Slf4j
@RestController
@RequestMapping("${adminPath}")
public class FallbackController {

    @Autowired
    private I18nHelper i18nHelper;

    /**
     * IP限流重定向
     *
     * @param request
     * @return
     */
    @RequestMapping("common/ip/fallback")
    public RestResponse ipFallback(ServerHttpRequest request) {
        String language = Optional.ofNullable(request.getHeaders().getFirst(HystrixConstant.LOCAL_KEY)).orElse(HystrixConstant.EN_US);
        i18nHelper.setLocale(language, null);
        RestResponse restResponse = new Failed("BOOK:COMMON:10019", i18nHelper.get("BOOK:COMMON:10019"));
        i18nHelper.removeLocale();
        return restResponse;
    }

    /**
     * url限流重定向
     *
     * @param request
     * @return
     */
    @RequestMapping("common/url/fallback")
    public RestResponse urlFallback(ServerHttpRequest request) {
        String language = request.getHeaders().getFirst(HystrixConstant.LOCAL_KEY);
        i18nHelper.setLocale(language, null);
        RestResponse restResponse = new Failed("BOOK:COMMON:10019", i18nHelper.get("BOOK:COMMON:10020"));
        i18nHelper.removeLocale();
        return restResponse;
    }

    /**
     * 属性限流重定向
     *
     * @param request
     * @return
     */
    @RequestMapping("common/property/fallback")
    public RestResponse propertyFallback(ServerHttpRequest request) {
        String language = request.getHeaders().getFirst(HystrixConstant.LOCAL_KEY);
        i18nHelper.setLocale(language, null);
        RestResponse restResponse = new Failed("BOOK:COMMON:10019", i18nHelper.get("BOOK:COMMON:10021"));
        i18nHelper.removeLocale();
        return restResponse;
    }
}
